package cn.kongwg.juc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author kongwg
 * @create 2021-04-22 18:25
 * <p>
 * <p>
 * * 三个线程启动 要求如下
 * * AA打印5次 BB打印10次 CC打印15次
 * *  接着
 * *  AA打印5次 BB打印10次 CC打印15次
 * *  ....来10轮
 * * >   1. 高内聚低耦合的前提下, 线程 操作 资源类
 * * >  2. 判断  干活  通知
 * * >  3. 多线程交互中 需要防止多线程的虚假唤醒 即判断资源状态使用while 不能用if
 * * >  4. 标志位
 */
public class ThreadOrderAccess {

    public static void main(String[] args) {
        ShareResource shareResource = new ShareResource();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                shareResource.print5();
            }
        }, "a").start();
        new Thread(() -> {
            for (int i = 0; i < 9; i++) {

                shareResource.print10();
            }
        }, "b").start();
        new Thread(() -> {
            for (int i = 0; i < 9; i++) {

                shareResource.print15();
            }
        }, "c").start();
    }
}


class ShareResource {
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    private Condition condition3 = lock.newCondition();
    private int number = 1;

    public void print5() {
        lock.lock();
        try {
            while (number != 1) {
                condition.await();
            }
            for (int i = 0; i < 5; i++) {
                System.out.println(Thread.currentThread().getName() + "\t" + i);
            }
            number = 2;
            condition2.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void print10() {
        lock.lock();
        try {
            while (number != 2) {
                condition.await();
            }
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName() + "\t" + i);
            }
            number = 3;
            condition3.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void print15() {
        lock.lock();
        try {
            while (number != 3) {
                condition.await();
            }
            for (int i = 0; i < 15; i++) {
                System.out.println(Thread.currentThread().getName() + "\t" + i);
            }
            number = 1;
            condition.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }
}
